package example.hello;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

public class Server extends UnicastRemoteObject implements Hello, Subject {
	private String data;
	
	private ArrayList<Observer> observers = new ArrayList<Observer>();
	
	public Server() throws RemoteException {
		super(1099);
		try {
			//Bind the remote object's stub in the registry
			Registry registry = LocateRegistry.createRegistry(1099);
			registry.rebind("HelloObserver", this);
		} catch (Exception e) {
			System.err.println("Server exception: " + e.toString());
			e.printStackTrace();
		}
	}
	
	public String sayHello() {
		return "Hello World!";
	}
	
	public String getData() {
		return data;
	}
	
	public void setData(String str) {
		data = str;
		
		try {
			notifyObservers();
		} catch (Exception e) {
			System.err.println(e);
		}
	}
	
	public void notifyObservers() throws RemoteException {
		for (Observer o: observers) {
			try {
				//o.update();
			} catch (Exception e) {
				System.err.println(e);
			}
		}
	}
	
	public void subcribe(Observer observer) throws RemoteException {
		observers.add(observer);
		System.err.println("number of observers " + observers.size());
		//System.err.println("add client " + observer.getName());
	}
	
	public void unsubcribe(Observer observer) throws RemoteException {
		observers.remove(observer);
	}
	
	public static void main(String[] args) {
		try {
			//Server obj = new Server();
			//Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 1100);
			
			Server obj = new Server();
			
			System.err.println("Server ready");			
		} catch (Exception e) {
			System.err.println("Server exception: " + e.toString());
			e.printStackTrace();
		}
	}	
}
